package au.com.bus4u.controller.admin;

import au.com.bus4u.controller.BaseController;
import au.com.bus4u.service.PermissionService;
import au.com.bus4u.service.RoleService;
import au.com.bus4u.utils.JsonResult;
import au.com.bus4u.utils.PageData;
import com.github.pagehelper.PageInfo;
import lombok.extern.java.Log;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author
 * @since 2019-09-24
 */
@RestController
@RequestMapping("/admin/role")
@Log
public class RoleController extends BaseController {

	@Autowired
	private RoleService roleService;
	
	@Autowired
	private PermissionService permissionService;
	
	
	/**
	 * 查询
	 */
	@RequiresPermissions("role:view")
	@RequestMapping("/loadAllRole")
	public PageData loadAllRole() throws Exception{
		log.info("=========================================");
//		IPage<Role> page=new Page<>(roleVo.getPage(), roleVo.getLimit());
//		QueryWrapper<Role> queryWrapper=new QueryWrapper<>();
//		queryWrapper.like(StringUtils.isNotBlank(roleVo.getName()), "name", roleVo.getName());
//		queryWrapper.like(StringUtils.isNotBlank(roleVo.getRemark()), "remark", roleVo.getRemark());
//		queryWrapper.eq(roleVo.getAvailable()!=null, "available", roleVo.getAvailable());
//		queryWrapper.orderByDesc("createtime");
//		this.roleService.page(page, queryWrapper);
//		return new DataGridView(page.getTotal(), page.getRecords());


		setPageHelperStartPage();
		PageData pageData = getPageData();
//		System.err.println("pageData = " + pageData);
		List<PageData> list = roleService.list(pageData);
		PageInfo<PageData> pageInfo = new PageInfo<>(list);//得到分页的结果对象
		List<PageData> pageList = pageInfo.getList();//获取返回页面的分页list数据
		PageData page = getPage(pageInfo);//获取分页数据page

		PageData result = new PageData();
		result.put("code",0);
		result.put("msg","");
		result.put("data",pageList);
		result.put("page",page);
		result.put("count",page.get("total"));//总条数 layui数据表分页组件需要

		return result;
	}
	
	
	/**
	 * 添加
	 */
	@RequiresPermissions("role:add")
	@RequestMapping("/addRole")
	public JsonResult addRole() throws Exception {
		log.info("=========================================");
//		try {
//			roleVo.setCreatetime(new Date());
//			this.roleService.save(roleVo);
//			return JsonResult.ADD_SUCCESS;
//		} catch (Exception e) {
//			e.printStackTrace();
//			return JsonResult.ADD_ERROR;
//		}
		PageData pd = getPageData();
//		System.err.println("pd = " + pd);
		roleService.save(pd);
		return new JsonResult(200,"新增成功");
	}
	/**
	 * 修改
	 */
	@RequiresPermissions("role:update")
	@RequestMapping("/updateRole")
	public JsonResult updateRole() throws Exception {
		log.info("=========================================");
//		try {
//			this.roleService.updateById(roleVo);
//			return JsonResult.UPDATE_SUCCESS;
//		} catch (Exception e) {
//			e.printStackTrace();
//			return JsonResult.UPDATE_ERROR;
//		}

		PageData pd = getPageData();
//		System.err.println("pd = " + pd);
		roleService.edit(pd);
		return new JsonResult(200,"更新成功");
	}
	
	/**
	 * 删除
	 */
	@RequiresPermissions("role:delete")
	@RequestMapping("/deleteRole")
	public JsonResult deleteRole(Integer id) throws Exception {
		log.info("=========================================");
//		try {
//			this.roleService.removeById(id);
//			return JsonResult.DELETE_SUCCESS;
//		} catch (Exception e) {
//			e.printStackTrace();
//			return JsonResult.DELETE_ERROR;
//		}
		return null;
	}
	
	
	/**
	 * 根据角色ID加载菜单和权限的树的json串
	 */
	@RequiresPermissions("role:view")
	@RequestMapping("/initPermissionByRoleId")
	public PageData initPermissionByRoleId(Integer role_id) throws Exception {
		log.info("=========================================");
		//查询所有可用的菜单和权限
		List<PageData> allPermissions = permissionService.loadAllMenuAndPermission();
//		System.out.println("查询所有可用的菜单和权限的个数:"+allPermissions.size());
//		System.out.println("role_id = [" + role_id + "]");
		//根据角色ID查询当前角色拥有的所有的权限或菜单ID
		List<Integer> currentRolePermissions = permissionService.queryRolePermissionIdsByRid(role_id);


		List<PageData> carrentPermissions=null;
		if(currentRolePermissions.size() > 0) { //如果有ID就去查询
			carrentPermissions = permissionService.loadAllPermissionByMenuIDS(currentRolePermissions);
		}else {
			carrentPermissions=new ArrayList<>();
		}
//		System.err.println("carrentPermissions = " + carrentPermissions);



//		//构造 List<TreeNode>
		List<PageData> nodes=new ArrayList<>();
		for (PageData p1 : allPermissions) {
			String checkArr="0";
			for (PageData p2 : carrentPermissions) {
				if(p1.getInt("menu_id") == p2.getInt("menu_id")) {
					checkArr="1";
					break;
				}
			}
			Boolean spread=(p1.getInt("spread")==null||p1.getInt("spread")==0)?false:true;
			p1.put("checkArr",checkArr);
			p1.put("spread",spread);

//			nodes.add(new TreeNode(p1.getId(), p1.getPid(), p1.getTitle(), spread, checkArr));
			nodes.add(p1);
		}
//		return new DataGridView(nodes);
		PageData result = new PageData();

		result.put("code",0);
		result.put("count",0);
		result.put("msg","");
		result.put("data",nodes);

		return result;
	}
	
	/**
	 * 保存角色和菜单权限之间的关系
	 */
	@RequiresPermissions("role:selectPermission")
	@RequestMapping("/saveRolePermission")
	public JsonResult saveRolePermission(Integer role_id,Integer[] ids) throws Exception {
		log.info("=========================================");
//		try {
//			this.roleService.saveRolePermission(rid,ids);
//			return JsonResult.DISPATCH_SUCCESS;
//		} catch (Exception e) {
//			e.printStackTrace();
//			return JsonResult.DISPATCH_ERROR;
//		}
		permissionService.saveRolePermission(role_id,ids);

		return new JsonResult(200,"分配成功");
	}
}

